package jspservlet.servlet;

import jspservlet.dao.UserDao;
import jspservlet.dao.impl.UserDaoImpl;
import jspservlet.vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {

    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException{
        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setPassword(req.getParameter("password"));

        UserDao dao=new UserDaoImpl();
        int flag = 0;
        try {
            flag = dao.queryByManagerName(user);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpSession session=req.getSession();
        if(flag == 1){
            session.setAttribute("username", user.getUsername());
            res.sendRedirect("./welcome.jsp");
        } else if(flag==0){
            session.setAttribute("usernameError", "wrong username, please try it again");
            res.sendRedirect("./login.jsp");
        }else if (flag==2){
            session.setAttribute("passwordError", "wrong password, please try it again");
            res.sendRedirect("./login.jsp");
        }
    }
}
